<!--
 * @Author: vn53el9 vn53el9@email.wal.mart.com
 * @Date: 2022-10-20 10:04:43
 * @LastEditors: Evan Liu
 * @LastEditTime: 2022-11-18 17:54:14
 * @FilePath: \ias_ui\src\views\coi\CBEC\index\edit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div v-loading="loading" class="CBEC">
    <div class="header">
      <div class="header-left">
        <el-button
          v-for="(item, index) in headerList"
          :key="index"
          v-anchor="{ id: item.id, el: '.goodsInfo' }"
          :class="current == index ? ' btn-active' : ''"
          type="text"
        >
          <strong>{{ item.label }}</strong>
        </el-button>
      </div>
      <!-- v-if="routerParam.type === 'edit'" -->
      <div v-if="!isDisabled" ref="headerRight" class="header-right">
        <el-button size="small" @click="goBack">返回</el-button>
        <el-button type="primary" size="small" @click="saveAsChannel">发布渠道</el-button>
      </div>
    </div>
    <div ref="goodsInfo" class="goodsInfo" @scroll.self="scrollFunc">
      <vendor id="anchor-1" ref="priceRef" :is-disabled="true" :goods-info="goodsInfo" />
      <div id="anchor-2">
        <baseInfo ref="baseInfoRef" :is-disabled="isDisabled" from-page="CBEC" class="baseInfo" :goods-info="goodsInfo" :gutter="20" :item-list="itemList" />
        <goodsAttribute ref="attrRef" :is-disabled="isDisabled" from-page="CBEC" :goods-info="goodsInfo" :gutter="20" />
      </div>
      <price id="anchor-3" ref="priceRef" :is-disabled="isDisabled" :goods-info="goodsInfo" />
      <productPicture id="anchor-4" ref="productPictureRef" :is-disabled="isDisabled" :goods-info="goodsPhotos" />
      <detailPicture id="anchor-5" ref="detailPictureRef" :is-disabled="isDisabled" :goods-info="goodsInfo.skuChannelInfos[0]" />
      <channelEdit
        v-for="(item, i) in goodsInfo.skuChannelInfos"
        :id="'anchor-' + (6 + i)"
        :key="'channel' + i"
        :ref="'channel' + i"
        :is-disabled="isDisabled"
        :channel-id="item.channelId"
        :goods-info="item"
      />
    </div>
  </div>
</template>

<script>
import baseInfo from '@/views/coi/making/baseInfo.vue'
import productPicture from '../components/productPicture'
import price from '../components/price'
import vendor from '../components/vendor'
import detailPicture from '../components/detailPicture'
import channelEdit from '../components/channel_edit'
import { baseInfo_CBEC } from '@/views/coi/commonJs/goodsInfo.js'
import goodsAttribute from '@/views/coi/making/goodsAttribute.vue'
import { initCBECSkuChannelInfoByChannel, saveAndPushCBECSkuInfo, findCBECSkuChannelInfoByUpc } from '@/api/coi/CBEC/maintainProducts'
import { findChgSkuInfoByProcessId } from '@/api/coi/onlineTaskAPI/sku'
import eventBus from '@/utils/eventBus'

export default {
  name: 'JDChannel',
  components: {
    baseInfo,
    goodsAttribute,
    productPicture,
    price,
    vendor,
    detailPicture,
    channelEdit
  },
  data() {
    return {
      headerList: [
        {
          label: '供应商',
          id: '1'
        },
        {
          label: `商品信息`,
          id: '2'
        },
        {
          label: '价格',
          id: '3'
        },
        {
          label: '商品图片',
          id: '4'
        },
        {
          label: '商品详情页',
          id: '5'
        }
      ],
      itemList: JSON.parse(JSON.stringify(baseInfo_CBEC)),
      goodsInfo: {
        priceHs: {},
        skuContentResources: [],
        skuContent: {
          content: ''
        },
        skuChannelInfos: []
      },
      goodsPhotos: {
        skuOptionResources: [], // 素材图
        transparentImg: [], // 透明
        skuResourcesImg: [] // 主图
      },
      current: 0,
      dialogVisible: false,
      loading: false,
      routerParam: {},
      isDisabled: false,
      operationCode: [100]
    }
  },
  computed: {},
  created() {
    this.itemList.forEach((item) => {
      if (item.label === '部门' || item.label === 'UPC(不含检验码)') item.disabled = true
    })
    this.routerParam = this.$route.params
    this.isDisabled = this.routerParam.type !== 'edit'
    this.getGoodsInfo()
  },
  mounted() {
    eventBus.$on('loadingChange', (loading) => {
      this.loading = loading
    })
    eventBus.$on('operationCodeChange', (path) => {
      if (path === 'skuContentResources') this.operationCode[1] = 140
      if (['skuResourcesImg', 'skuOptionResources', 'transparentImg'].indexOf(path) !== -1) this.operationCode[2] = 150
    })
  },
  methods: {
    goBack() {
      console.log(this.routerParam.fromTab)
      this.$router.push({
        name: this.routerParam.fromPage,
        params: { tab: this.routerParam.fromTab, type: 'sku' }
      })
    },
    async getGoodsInfo() {
      try {
        this.loading = true
        const param = { upc: this.routerParam.upc, channelId: this.$route.query.channelId }
        const { code, result } =
          this.routerParam.fromPage === 'ChannelInventory'
            ? this.routerParam.type === 'edit'
              ? await initCBECSkuChannelInfoByChannel(param)
              : await findCBECSkuChannelInfoByUpc(param)
            : await findChgSkuInfoByProcessId(param.upc)
        if (code !== '0') return
        this.setQueryData(result)
      } catch (error) {
        this.$message({
          type: 'error',
          message: error.message
        })
        // this.goBack()
      } finally {
        this.loading = false
      }
    },
    setQueryData(result) {
      const list = []
      if ('transportMode' in result) result.transportMode = result.transportMode === null ? '' : result.transportMode + ''
      result.skuChannelInfos.forEach((item, index) => {
        if (Number(item.channelId) > 0) {
          list.push(item)
          if (item.channelName) this.headerList.push({ label: item.channelName, id: index + 6 + '' })
        }
        // skuEditFlag个位
        item.channelAttributeList = item.channelAttributeList.filter((_) => {
          return parseInt(_.skuEditFlag.toString().charAt(_.skuEditFlag.toString().length - 1)) === 1
        })
        // 过滤分类照片
        this.goodsPhotos.skuOptionResources =
          item.skuOptionResources?.sort((a, b) => {
            return a.sort - b.sort
          }) || [] // 素材图
        this.goodsPhotos.transparentImg = item.skuResources?.filter((el) => el.resourceType === 3) || [] // 透明
        this.goodsPhotos.skuResourcesImg =
          item.skuResources
            ?.filter((el) => el.resourceType === 1)
            .sort((a, b) => {
              return a.sort - b.sort
            }) || [] // 主图
      })
      this.goodsInfo = result
      if (!this.goodsInfo.priceHs) this.goodsInfo.priceHs = {}
      this.$set(this.goodsInfo, 'skuChannelInfos', list)
    },
    validateFunc() {
      let bol = true
      for (let i = 0; i < this.goodsInfo.skuChannelInfos.length; i++) {
        const attrRef = 'channel' + i
        if (!this.$refs[attrRef][0].submitForm()) {
          bol = false
          break
        }
      }
      return (
        this.$refs.baseInfoRef.submitForm() &&
        this.$refs.attrRef.submitForm() &&
        this.$refs.priceRef.submitForm() &&
        this.$refs.productPictureRef.submitForm() &&
        this.$refs.detailPictureRef.submitForm() &&
        bol
      )
    },
    async saveAsChannel() {
      try {
        if (this.validateFunc()) {
          this.loading = true
          const param = this.tansGoodsPhoto()
          param.operationCode = this.checkOperationCode(this.operationCode)
          const result = await saveAndPushCBECSkuInfo(param)
          if (result.code !== '0') return
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          this.$router.push({ name: this.routerParam.fromPage, params: { tab: this.routerParam.fromTab } })
        }
      } finally {
        this.loading = false
      }
    },
    checkOperationCode(operationCode) {
      let bol = false
      let bol2 = false
      let bol3 = false
      let code = null
      let codes = 0
      operationCode.forEach((item, i) => {
        if (item !== null) {
          code = item
          if (i === 0) {
            bol = true
          }
          if (i === 1 && bol) {
            bol2 = true
            code = 110
          }
          if (i === 2 && bol) {
            bol3 = true
            code = 120
          }
          if (bol2 && bol3) {
            code = 160
          }
          codes++
        }
      })
      if (codes === 3) {
        code = 130
      }
      return code
    },
    tansGoodsPhoto() {
      const goodsData = JSON.parse(JSON.stringify(this.goodsInfo))
      this.goodsPhotos.skuResourcesImg.forEach((item, index) => {
        item.sort = index
        item.resourceType = 1
      })
      this.goodsPhotos.skuOptionResources.forEach((item, index) => {
        item.resourceType = 2
      })
      this.goodsPhotos.transparentImg.forEach((item, index) => {
        item.resourceType = 3
      })
      goodsData.skuChannelInfos[0].skuResources = [...this.goodsPhotos.skuResourcesImg, ...this.goodsPhotos.transparentImg]
      goodsData.skuChannelInfos[0].skuOptionResources = this.goodsPhotos.skuOptionResources
      goodsData.taxPrice = Number(goodsData.taxPrice)
      goodsData.itemTotalWeight = Number(goodsData.itemTotalWeight)
      return goodsData
    },
    scrollFunc() {
      const domList = document.querySelectorAll("[id^='anchor']")
      const contentList = [...domList].map((_) => _.offsetTop + _.offsetHeight)
      const scrollHeight = this.$refs.goodsInfo.scrollHeight
      const height = this.$refs.goodsInfo.clientHeight
      const top = this.$refs.goodsInfo.scrollTop
      if (top + height === scrollHeight) {
        this.current = domList.length - 1
      } else {
        this.current = contentList.findIndex((_) => _ > top) || 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.CBEC {
  .header {
    margin: 0 12px;
    display: flex;
    justify-content: space-between;
    .header-left {
      z-index: 2;
      padding: 5px;
      /deep/ .el-button--text {
        margin: 0;
        margin-right: 10px;
        color: #000203;
      }
    }
    .header-right {
      display: flex;
      align-items: center;
    }
  }
  .goodsInfo {
    height: calc(100vh - 95px);
    position: relative;
    &::-webkit-scrollbar {
      width: 8px;
    }
    margin-left: 16px;
    overflow-y: auto;
    flex: 1;
  }
}
/deep/ .btn-active {
  color: #0071ce !important;
}
strong {
  font-size: 16px;
  font-weight: 600;
}
.app-main {
  overflow: hidden !important;
}
</style>
